<template>
  <div class="travel-agent-page">
    <el-container style="height: 100vh;">
      <!-- 头部 -->
      <el-header class="header">
        <div class="header-content">
          <el-button type="primary" @click="goHome" icon="el-icon-back" circle></el-button>
          <div class="header-title">
            <h2>AI旅游智能体</h2>
            <p>专业的步骤化旅游规划助手</p>
          </div>
          <el-button type="success" @click="clearChat" icon="el-icon-refresh" circle></el-button>
        </div>
      </el-header>

      <!-- 主聊天区域 -->
      <el-main class="chat-main">
        <div class="chat-container">
          <!-- 聊天消息区域 -->
          <div class="messages-container" ref="messagesContainer">
            <div v-if="messages.length === 0" class="welcome-message">
              <div class="welcome-content">
                <i class="el-icon-s-grid"></i>
                <h3>欢迎使用AI旅游智能体</h3>
                <p>我是您的专业旅游规划师，将为您提供：</p>
                <div class="features-grid">
                  <div class="feature-item">
                    <i class="el-icon-location"></i>
                    <span>目的地分析</span>
                  </div>
                  <div class="feature-item">
                    <i class="el-icon-date"></i>
                    <span>行程规划</span>
                  </div>
                  <div class="feature-item">
                    <i class="el-icon-wallet"></i>
                    <span>预算建议</span>
                  </div>
                  <div class="feature-item">
                    <i class="el-icon-guide"></i>
                    <span>专业建议</span>
                  </div>
                </div>
                <p>请描述您的旅游需求，我将为您制定详细的旅游方案！</p>
              </div>
            </div>
            
            <div 
              v-for="(message, index) in messages" 
              :key="index"
              :class="['message-item', message.role]"
            >
              <div class="message-content">
                <div v-if="message.role === 'user'" class="user-message">
                  {{ message.content }}
                </div>
                <div v-else class="assistant-message">
                  <div class="assistant-avatar">
                    <i class="el-icon-s-custom"></i>
                  </div>
                  <div class="assistant-content">
                    <!-- 智能体步骤显示 -->
                    <div v-if="message.steps && message.steps.length > 0" class="steps-container">
                      <div class="steps-summary">共 {{ message.steps.length }} 个步骤</div>
                      <div 
                        v-for="(step, stepIndex) in message.steps" 
                        :key="stepIndex"
                        :class="['step-item', { 'step-active': step.isActive, 'step-completed': step.isCompleted }]"
                      >
                        <div class="step-header" @click="toggleStep(stepIndex)">
                          <div class="step-number">
                            <span v-if="step.isCompleted">✓</span>
                            <span v-else-if="step.isActive" class="loading-dot"></span>
                            <span v-else>{{ stepIndex + 1 }}</span>
                          </div>
                          <div class="step-title">
                            第{{ stepIndex + 1 }}步: {{ step.title }}
                            <!-- 只有当标题不包含"完成了它的任务"时才显示工具信息 -->
                            <span v-if="step.currentTool && !step.title.includes('完成了它的任务')" class="tool-info">工具: {{ step.currentTool }}</span>
                          </div>
                          <div class="step-toggle">
                            <i :class="step.isExpanded ? 'el-icon-arrow-up' : 'el-icon-arrow-down'"></i>
                          </div>
                        </div>
                        <div 
                          v-if="step.content && step.isExpanded" 
                          class="step-content" 
                          v-html="formatMessage(step.content)"
                        ></div>
                        <div v-if="step.isActive && step.isLoading" class="step-loading">
                          <div class="typing-indicator">
                            <span></span>
                            <span></span>
                            <span></span>
                          </div>
                        </div>
                      </div>
                    </div>
                    <!-- 最终响应显示 -->
                    <div v-if="message.content && message.content.includes('=== 智能体最终响应 ===')" class="final-response-bubble" v-html="formatFinalResponse(message.content)"></div>
                    <!-- 普通消息显示 -->
                    <div v-else-if="message.content" class="message-text" v-html="formatMessage(message.content)"></div>
                  </div>
                </div>
              </div>
            </div>
          </div>

          <!-- 输入区域 -->
          <div class="input-container">
            <div class="input-box">
              <el-input
                v-model="inputMessage"
                type="textarea"
                :rows="3"
                placeholder="请详细描述您的旅游需求，如：目的地、时间、预算、兴趣等..."
                                @keydown.ctrl.enter.native="sendMessage"
                :disabled="isLoading"
                maxlength="1000"
                show-word-limit
              ></el-input>
              <div class="input-actions">
                <div class="input-tips">
                  <span>💡 提示：提供更详细的信息，可以获得更精准的规划建议</span>
                </div>
                <el-button 
                  type="primary" 
                  @click="sendMessage" 
                  :loading="isLoading"
                  :disabled="!inputMessage.trim()"
                >
                  开始规划 (Ctrl+Enter)
                </el-button>
              </div>
            </div>
          </div>
        </div>
      </el-main>
    </el-container>
  </div>
</template>

<script>
import { getSSEURL } from '@/config/apiConfig'

export default {
  name: 'TravelAgent',
  data() {
    return {
      inputMessage: '',
      messages: [],
      isLoading: false,
      sseSource: null,
      currentStepIndex: -1,
      currentMessage: null,
      isReceivingFinalResponse: false,
      finalResponseContent: ''
    }
  },
  beforeDestroy() {
    this.cleanupConnection()
    // 移除页面离开监听器
    window.removeEventListener('beforeunload', this.handlePageLeave)
  },
  beforeUnmount() {
    // Vue 3 兼容
    this.cleanupConnection()
    window.removeEventListener('beforeunload', this.handlePageLeave)
  },
  mounted() {
    // 添加页面离开监听器
    this.handlePageLeave = () => {
      this.cleanupConnection()
    }
    window.addEventListener('beforeunload', this.handlePageLeave)
  },
  methods: {
    clearChat() {
      this.$confirm('确定要清空当前对话吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }).then(() => {
        this.messages = []
        this.inputMessage = ''
        this.cleanupConnection()
        this.$message.success('对话已清空')
      }).catch(() => {})
    },
    
    goHome() {
      // 离开页面前清理连接
      this.cleanupConnection()
      this.$router.push('/')
    },
    
    async sendMessage() {
      if (!this.inputMessage.trim() || this.isLoading) return
      
      const userMessage = {
        role: 'user',
        content: this.inputMessage.trim(),
        timestamp: new Date()
      }
      
      this.messages.push(userMessage)
      
      // 添加智能体消息占位符
      const assistantMessage = {
        role: 'assistant',
        content: '',
        steps: [],
        timestamp: new Date()
      }
      this.messages.push(assistantMessage)
      this.currentMessage = assistantMessage
      
      const messageToSend = this.inputMessage.trim()
      this.inputMessage = ''
      this.isLoading = true
      this.currentStepIndex = -1
      
      this.scrollToBottom()
      
      try {
        await this.sendSSEMessage(messageToSend)
      } catch (error) {
        this.$message.error('发送消息失败：' + error.message)
        assistantMessage.content = '抱歉，智能体服务暂时不可用，请稍后再试。'
      } finally {
        this.isLoading = false
      }
    },
    
    sendSSEMessage(message) {
      return new Promise((resolve, reject) => {
        // 关闭之前的连接
        this.cleanupConnection()
        
        // 使用统一的SSE URL配置，修正端点名称
        const url = getSSEURL(`/ai/chat/manus/sse?message=${encodeURIComponent(message)}`)
        
        console.log('创建 Agent SSE 连接:', url)
        
        try {
          this.sseSource = new EventSource(url)
          
          this.sseSource.onopen = () => {
            console.log('智能体SSE连接已建立')
          }
          
          this.sseSource.onmessage = (event) => {
            try {
              const data = event.data
              console.log('智能体SSE收到数据:', data)
              
              // 处理正常数据
              if (data && data.trim()) {
                this.processStreamData(data)
                this.scrollToBottom()
                // 强制触发Vue响应式更新
                this.$forceUpdate()
              }
            } catch (error) {
              console.error('解析智能体SSE数据失败:', error, 'Original data:', event.data)
            }
          }
          
          this.sseSource.onerror = (error) => {
            console.log('智能体SSE连接结束或错误:', error)
            console.log('EventSource readyState:', this.sseSource ? this.sseSource.readyState : 'null')
            
            // 检查是否正在接收最终响应，如果是则将其添加到内容中
            if (this.isReceivingFinalResponse && this.finalResponseContent) {
              this.currentMessage.content += this.finalResponseContent;
              this.isReceivingFinalResponse = false;
              this.finalResponseContent = '';
              // 强制触发Vue响应式更新
              this.$forceUpdate();
            }
            
            // 检查是否已有内容
            const hasContent = this.currentMessage.content.trim() || 
                             (this.currentMessage.steps && this.currentMessage.steps.length > 0)
            
            if (hasContent) {
              console.log('智能体SSE正常结束: 已有部分内容')
              // 这是正常的结束方式，不显示错误信息
            } else {
              // 没有收到任何内容
              console.error('智能体SSE连接失败: 未收到任何数据')
              this.currentMessage.content = '连接失败，请稍后重试。'
            }
            
            // 完成所有步骤
            this.completeAllSteps()
            
            if (this.sseSource) {
              this.sseSource.close()
              this.sseSource = null
            }
            
            // 根据情况决定resolve或reject
            if (hasContent) {
              // 如果已有内容，认为正常结束
              resolve()
            } else {
              reject(new Error('连接失败'))
            }
          }
          
        } catch (error) {
          console.error('创建智能体SSE连接失败:', error)
          this.completeAllSteps()
          reject(error)
        }
      })
    },
    
    cleanupConnection() {
      if (this.sseSource) {
        console.log('清理SSE连接')
        this.sseSource.close()
        this.sseSource = null
      }
    },
    
    processStreamData(data) {
      // 检查是否是新步骤的开始 (Step X: ...)
      const stepMatch = data.match(/^Step\s+(\d+):\s*(.*)/)
      if (stepMatch) {
        const stepNumber = parseInt(stepMatch[1])
        const stepContent = stepMatch[2]
        
        // 完成上一个步骤
        if (this.currentStepIndex >= 0 && this.currentMessage.steps[this.currentStepIndex]) {
          this.currentMessage.steps[this.currentStepIndex].isActive = false
          this.currentMessage.steps[this.currentStepIndex].isCompleted = true
          this.currentMessage.steps[this.currentStepIndex].isLoading = false
        }
        
        // 解析步骤标题和结果内容
        let stepTitle = `步骤 ${stepNumber}`
        let resultContent = stepContent
        
        // 检查是否包含工具完成信息和结果
        const toolResultMatch = stepContent.match(/(工具\s+\w+\s+完成了它的任务！)(?:结果:\s*"([\s\S]*?)")?/)
        if (toolResultMatch) {
          stepTitle = toolResultMatch[1]  // 工具 getOSInfo 完成了它的任务！
          if (toolResultMatch[2]) {
            resultContent = toolResultMatch[2]  // Windows
          }
        }
        
        // 添加新步骤
        const newStep = {
          title: stepTitle,
          content: resultContent,
          isActive: true,
          isCompleted: false,
          isLoading: true,
          currentTool: null,
          isExpanded: false // 默认折叠
        }
        
        // 提取工具名称
        const toolNameMatch = stepTitle.match(/工具\s+(\w+)\s+完成了它的任务！/)
        if (toolNameMatch) {
          newStep.currentTool = toolNameMatch[1]
        }
        
        this.currentMessage.steps.push(newStep)
        this.currentStepIndex = this.currentMessage.steps.length - 1
      } else {
        // 处理非步骤消息
        const trimmedData = data.trim();
        
        // 检查是否是智能体最终响应的开始
        if (trimmedData.startsWith('=== 智能体最终响应 ===')) {
          // 完成所有步骤
          this.completeAllSteps();
          // 初始化最终响应内容（保留原始数据格式）
          this.finalResponseContent = data + '\n';
          // 设置标志表示正在接收最终响应
          this.isReceivingFinalResponse = true;
        } 
        // 检查是否是智能体最终响应的结束
        else if (trimmedData.startsWith('=== 响应结束 ===') && this.isReceivingFinalResponse) {
          // 将完整的最终响应添加到主消息内容
          this.finalResponseContent += data + '\n';
          this.currentMessage.content += this.finalResponseContent;
          // 重置标志
          this.isReceivingFinalResponse = false;
          this.finalResponseContent = '';
          // 强制触发Vue响应式更新
          this.$forceUpdate();
        }
        // 检查是否正在接收最终响应内容
        else if (this.isReceivingFinalResponse) {
          // 继续累积最终响应内容（保留原始数据格式）
          this.finalResponseContent += data + '\n';
        }
        else {
          // 非步骤开始消息，添加到当前步骤内容或主消息内容
          if (this.currentStepIndex >= 0 && this.currentMessage.steps[this.currentStepIndex]) {
            // 添加到当前步骤内容
            this.currentMessage.steps[this.currentStepIndex].content += '\n' + data
            
            // 检查是否是工具完成消息，更新步骤信息
            const toolCompleteMatch = data.match(/工具\s+(\w+)\s+完成了它的任务！/)
            if (toolCompleteMatch) {
              const toolName = toolCompleteMatch[1]
              this.currentMessage.steps[this.currentStepIndex].currentTool = toolName
              this.currentMessage.steps[this.currentStepIndex].title = `工具 ${toolName} 完成了它的任务！`
            }
            
            // 检查是否是执行结束或异常消息
            if (data.startsWith('执行结束:') || data.startsWith('执行出现异常:')) {
              this.currentMessage.steps[this.currentStepIndex].isActive = false
              this.currentMessage.steps[this.currentStepIndex].isCompleted = true
              this.currentMessage.steps[this.currentStepIndex].isLoading = false
            }
          } else {
            // 没有活动步骤，添加到主消息内容
            this.currentMessage.content += data + '\n'
          }
        }
      }
      
      this.scrollToBottom()
    },
    
    completeAllSteps() {
      if (this.currentMessage && this.currentMessage.steps) {
        this.currentMessage.steps.forEach(step => {
          step.isActive = false
          step.isCompleted = true
          step.isLoading = false
        })
      }
    },
    
    toggleStep(stepIndex) {
      if (this.currentMessage && this.currentMessage.steps && this.currentMessage.steps[stepIndex]) {
        // 使用 Vue.set 确保响应式更新
        this.$set(this.currentMessage.steps[stepIndex], 'isExpanded', !this.currentMessage.steps[stepIndex].isExpanded)
      }
    },
    
    formatMessage(content) {
      if (!content) return ''
      
      let formattedContent = content
      
      // 处理工具完成信息，将结果内容设置为可折叠
      // 修改正则表达式以正确匹配您提供的数据格式，支持多行结果内容
      formattedContent = formattedContent.replace(
        /工具\s+(\w+)\s+完成了它的任务！结果:\s*"([\s\S]*?)"/g,
        '<div class="tool-result"><details><summary class="tool-header">🔧 工具: <strong>$1</strong> 完成了它的任务！</summary><div class="tool-content">$2</div></details></div>'
      )
      
      // 处理智能体最终响应内容（完整格式）
      formattedContent = formattedContent.replace(
        /===\s*智能体最终响应\s*===([\s\S]*?)===\s*响应结束\s*===/g,
        '<div class="final-response">$1</div>'
      )
      
      // 处理智能体最终响应内容（可能分段接收的情况）
      // 检查是否包含开始标记但不包含结束标记
      if (/(===\s*智能体最终响应\s*===)/.test(formattedContent) && !/(===\s*响应结束\s*===)/.test(formattedContent)) {
        formattedContent = formattedContent.replace(
          /(===\s*智能体最终响应\s*===)([\s\S]*)/g,
          '<div class="final-response">$2'
        )
      }
      
      // 检查是否包含结束标记但不包含开始标记
      if (!/(===\s*智能体最终响应\s*===)/.test(formattedContent) && /(===\s*响应结束\s*===)/.test(formattedContent)) {
        formattedContent = formattedContent.replace(
          /([\s\S]*)(===\s*响应结束\s*===)/g,
          '$1</div>'
        )
      }
      
      // 处理搜索关键词
      if (formattedContent.includes('Web search results for')) {
        formattedContent = formattedContent.replace(
          /Web search results for '([^']+)':/g,
          '<div class="search-query">🔍 搜索关键词：<strong>$1</strong></div>'
        )
      }
      
      // 处理搜索结果项 - 使用分行处理
      const lines = formattedContent.split('\\n')
      let resultHtml = []
      let i = 0
      
      while (i < lines.length) {
        const line = lines[i].trim()
        
        // 检查是否是搜索结果项的开始 (数字. 标题)
        const titleMatch = line.match(/^(\d+)\.\s*(.+)$/)
        if (titleMatch && i + 2 < lines.length) {
          const number = titleMatch[1]
          const title = titleMatch[2]
          
          // 查找Description和URL行
          let descLine = ''
          let urlLine = ''
          
          if (lines[i + 1] && lines[i + 1].trim().startsWith('Description:')) {
            descLine = lines[i + 1].trim().replace('Description: ', '')
          }
          if (lines[i + 2] && lines[i + 2].trim().startsWith('URL:')) {
            urlLine = lines[i + 2].trim().replace('URL: ', '')
          }
          
          if (descLine && urlLine) {
            // 生成格式化的搜索结果项
            resultHtml.push(`<div class="search-item">
              <div class="search-title">
                <span class="search-number">${number}</span> 
                <strong>${title}</strong>
              </div>
              <div class="search-desc">${descLine}</div>
              <div class="search-url">
                <a href="${urlLine}" target="_blank">🔗 查看详情</a>
              </div>
            </div>`)
            i += 3 // 跳过已处理的3行
            continue
          }
        }
        
        resultHtml.push(line)
        i++
      }
      
      // 处理新的搜索结果格式（您提供的数据格式）
      if (formattedContent.includes('搜索结果:')) {
        const sections = formattedContent.split('搜索结果:')
        if (sections.length > 1) {
          let newContent = sections[0]
          for (let s = 1; s < sections.length; s++) {
            newContent += '搜索结果:<br>'
            const sectionLines = sections[s].split('\\n')
            for (let j = 0; j < sectionLines.length; j++) {
              const line = sectionLines[j].trim()
              if (line) {
                // 检查是否是数字开头的列表项
                if (/^\d+\./.test(line)) {
                  newContent += `<div class="search-item">${line}</div>`
                } else {
                  newContent += line + '<br>'
                }
              }
            }
          }
          formattedContent = newContent
        }
      }
      
      if (resultHtml.length > 0) {
        formattedContent = resultHtml.join('<br>')
      }
      
      // 基本格式化
      formattedContent = formattedContent
        .replace(/\\n/g, '<br>') // 处理转义的换行符
        .replace(/\n\s*\n/g, '<br><br>') // 多个连续换行保留段落间距
        .replace(/\n/g, '<br>') // 单个换行转为<br>
        .replace(/\*\*(.*?)\*\*/g, '<strong>$1</strong>') // 粗体
        .replace(/\*(.*?)\*/g, '<em>$1</em>') // 斜体
        .replace(/`(.*?)`/g, '<code>$1</code>') // 代码
      
      return formattedContent
    },
    
    formatFinalResponse(content) {
      if (!content) return ''
      
      // 提取最终响应内容（去除开始和结束标记）
      let finalContent = content
        .replace(/===\s*智能体最终响应\s*===/g, '')
        .replace(/===\s*响应结束\s*===/g, '')
        .trim()
      
      // 基本格式化
      finalContent = finalContent
        .replace(/\\n/g, '<br>') // 处理转义的换行符
        .replace(/\n\s*\n/g, '<br><br>') // 多个连续换行保留段落间距
        .replace(/\n/g, '<br>') // 单个换行转为<br>
        .replace(/\*\*(.*?)\*\*/g, '<strong>$1</strong>') // 粗体
        .replace(/\*(.*?)\*/g, '<em>$1</em>') // 斜体
        .replace(/`(.*?)`/g, '<code>$1</code>') // 代码
      
      return finalContent
    },
    
    scrollToBottom() {
      this.$nextTick(() => {
        const container = this.$refs.messagesContainer
        if (container) {
          container.scrollTop = container.scrollHeight
        }
      })
    }
  }
}
</script>

<style scoped>
.travel-agent-page {
  height: 100vh;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
}

.header {
  background: rgba(255, 255, 255, 0.95);
  border-bottom: 1px solid #e8e8e8;
  padding: 0 30px;
}

.header-content {
  display: flex;
  align-items: center;
  justify-content: space-between;
  height: 100%;
}

.header-title {
  text-align: center;
  flex: 1;
}

.header-title h2 {
  margin: 0 0 5px 0;
  color: #333;
  font-size: 24px;
}

.header-title p {
  margin: 0;
  color: #666;
  font-size: 14px;
}

.chat-main {
  background: #fff;
  padding: 0;
}

.chat-container {
  height: 100%;
  display: flex;
  flex-direction: column;
}

.messages-container {
  flex: 1;
  overflow-y: auto;
  padding: 20px;
}

.message-item {
  margin-bottom: 10px;
}

.message-item.user {
  text-align: right;
}

.user-message {
  display: inline-block;
  max-width: 70%;
  padding: 8px 12px;
  background: #667eea;
  color: white;
  border-radius: 14px;
  word-wrap: break-word;
  font-size: 13px;
}

.assistant-message {
  display: flex;
  align-items: flex-start;
  max-width: 90%;
}

.assistant-avatar {
  width: 28px;
  height: 28px;
  border-radius: 50%;
  background: linear-gradient(45deg, #667eea, #764ba2);
  display: flex;
  align-items: center;
  justify-content: center;
  margin-right: 8px;
  color: white;
  font-size: 12px;
}

.assistant-content {
  flex: 1;
}

.welcome-message {
  text-align: center;
  padding: 20px 15px;
  color: #666;
}

.welcome-content i {
  font-size: 28px;
  color: #667eea;
  margin-bottom: 12px;
}

.welcome-content h3 {
  margin: 0 0 12px 0;
  color: #333;
  font-size: 18px;
}

.features-grid {
  display: grid;
  grid-template-columns: repeat(2, 1fr);
  gap: 12px;
  max-width: 400px;
  margin: 15px auto;
}

.feature-item {
  display: flex;
  align-items: center;
  padding: 10px;
  background: #f8f9fa;
  border-radius: 5px;
  color: #555;
  font-size: 12px;
}

.feature-item i {
  font-size: 16px;
  margin-right: 6px;
  color: #667eea;
}

.steps-container {
  background: #f8f9fa;
  border-radius: 6px;
  padding: 6px;
  border: 1px solid #e9ecef;
  margin-bottom: 8px;
}

.steps-summary {
  font-weight: 600;
  color: #333;
  margin-bottom: 6px;
  padding-bottom: 4px;
  border-bottom: 1px solid #e9ecef;
  font-size: 12px;
}

.step-item {
  margin-bottom: 6px;
  padding: 8px;
  background: white;
  border-radius: 4px;
  border-left: 2px solid #e9ecef;
  transition: all 0.3s ease;
}

.step-item.step-active {
  border-left-color: #667eea;
  box-shadow: 0 1px 3px rgba(102, 126, 234, 0.15);
}

.step-item.step-completed {
  border-left-color: #28a745;
}

.step-title {
  font-weight: 600;
  color: #333;
  font-size: 11px;
  display: flex;
  align-items: center;
  flex-wrap: wrap;
  gap: 3px;
}

.tool-info {
  display: inline-block;
  padding: 1px 3px;
  background: #e8f5e8;
  border: 1px solid #4caf50;
  border-radius: 6px;
  font-size: 9px;
  color: #2e7d32;
  font-weight: normal;
  white-space: nowrap;
  margin-left: 6px;
}

.step-content {
  margin-top: 3px;
  line-height: 1.2;
  color: #555;
  white-space: normal;
  word-wrap: break-word;
  font-size: 11px;
}

.step-content code {
  background: #f4f4f4;
  padding: 0px 2px;
  border-radius: 1px;
  font-family: monospace;
  font-size: 0.75em;
}

.step-header {
  display: flex;
  align-items: center;
  margin-bottom: 3px;
  cursor: pointer;
  transition: background-color 0.2s ease;
  padding: 1px;
  border-radius: 1px;
}

.step-header:hover {
  background-color: #f8f9fa;
}

.step-toggle {
  margin-left: auto;
  color: #999;
  font-size: 10px;
  transition: transform 0.2s ease;
}

.step-toggle i {
  transition: transform 0.2s ease;
}

.step-number {
  width: 20px;
  height: 20px;
  border-radius: 50%;
  background: #e9ecef;
  display: flex;
  align-items: center;
  justify-content: center;
  margin-right: 8px;
  font-size: 10px;
  font-weight: 600;
  color: #666;
}

.step-item.step-active .step-number {
  background: #667eea;
  color: white;
}

.step-item.step-completed .step-number {
  background: #28a745;
  color: white;
}

.loading-dot {
  width: 4px;
  height: 4px;
  background: white;
  border-radius: 50%;
  animation: pulse 1.5s infinite;
}

@keyframes pulse {
  0%, 100% { opacity: 1; }
  50% { opacity: 0.5; }
}

.step-title {
  font-weight: 600;
  color: #333;
  font-size: 12px;
  display: flex;
  align-items: center;
  flex-wrap: wrap;
  gap: 4px;
}

.tool-info {
  display: inline-block;
  padding: 1px 4px;
  background: #e8f5e8;
  border: 1px solid #4caf50;
  border-radius: 8px;
  font-size: 10px;
  color: #2e7d32;
  font-weight: normal;
  white-space: nowrap;
}

.step-content {
  margin-top: 4px;
  line-height: 1.2;
  color: #555;
  white-space: normal;
  word-wrap: break-word;
  font-size: 12px;
}

.step-content code {
  background: #f4f4f4;
  padding: 1px 2px;
  border-radius: 2px;
  font-family: monospace;
  font-size: 0.8em;
}

.step-content strong {
  font-weight: 600;
  color: #333;
}

.step-content em {
  font-style: italic;
  color: #666;
}

.step-loading {
  margin-top: 8px;
}

.message-text {
  padding: 12px 16px;
  background: #f8f8f8;
  border-radius: 18px;
  word-wrap: break-word;
  line-height: 1.4;
  white-space: normal; /* 改为正常换行模式 */
}

.message-text code {
  background: #e8e8e8;
  padding: 2px 4px;
  border-radius: 3px;
  font-family: monospace;
  font-size: 0.9em;
}

.message-text strong {
  font-weight: 600;
  color: #333;
}

.message-text em {
  font-style: italic;
  color: #666;
}

/* 工具结果样式 */
.tool-result {
  margin: 4px 0;
  border: 1px solid #e9ecef;
  border-radius: 4px;
  overflow: hidden;
}

.tool-header {
  background: #f8f9fa;
  padding: 3px 6px;
  border-bottom: 1px solid #e9ecef;
  font-weight: 600;
  color: #495057;
  font-size: 11px;
  cursor: pointer;
}

.tool-content {
  padding: 5px;
  white-space: pre-wrap;
  word-wrap: break-word;
  font-size: 10px;
  line-height: 1.2;
}

.final-response-bubble {
  background: #e8f5e8;
  border: 1px solid #4caf50;
  border-radius: 6px;
  padding: 8px;
  margin: 8px 0;
  box-shadow: 0 1px 2px rgba(0,0,0,0.1);
  font-size: 11px;
  line-height: 1.3;
}

.final-response-bubble a {
  display: inline-block;
  background: #4caf50;
  color: white;
  padding: 5px 10px;
  border-radius: 3px;
  text-decoration: none;
  font-weight: bold;
  margin: 6px 0;
  transition: background-color 0.3s;
  font-size: 10px;
}

.final-response-bubble a:hover {
  background: #45a049;
}

.final-response-bubble h3 {
  margin-top: 0;
  color: #2e7d32;
  font-size: 13px;
  margin-bottom: 5px;
}

.final-response-bubble p {
  margin: 3px 0;
  line-height: 1.3;
}

.search-query {
  background: #e3f2fd;
  padding: 3px 5px;
  border-radius: 2px;
  margin-bottom: 5px;
  color: #1976d2;
  font-size: 10px;
  line-height: 1.2;
}

.search-item {
  background: #fff;
  border: 1px solid #e0e0e0;
  border-radius: 3px;
  padding: 6px;
  margin-bottom: 3px;
  transition: box-shadow 0.2s ease;
  line-height: 1.2;
}

.search-title strong {
  color: #333;
  line-height: 1.2;
  font-size: 11px;
}

.search-desc {
  color: #666;
  font-size: 10px;
  line-height: 1.2;
  margin-bottom: 3px;
  margin-left: 18px;
}

.search-url a {
  color: #667eea;
  text-decoration: none;
  font-size: 9px;
  font-weight: 500;
  padding: 1px 3px;
  border-radius: 2px;
  border: 1px solid #667eea;
  transition: all 0.2s ease;
}

.search-url a:hover {
  background: #667eea;
  color: white;
  text-decoration: none;
}

/* 可折叠详情样式 */
details {
  border: none;
}

summary {
  outline: none;
  cursor: pointer;
  list-style: none;
}

summary::-webkit-details-marker {
  display: none;
}

summary::after {
  content: " ▼";
  float: right;
  transition: transform 0.2s;
}

details[open] summary::after {
  transform: rotate(180deg);
}

details[open] summary {
  border-bottom: 1px solid #e9ecef;
  padding-bottom: 8px;
  margin-bottom: 8px;
}

.typing-indicator {
  display: flex;
  padding: 8px 0;
  align-items: center;
}

.typing-indicator span {
  width: 6px;
  height: 6px;
  border-radius: 50%;
  background: #999;
  margin: 0 2px;
  animation: typing 1.4s infinite ease-in-out;
}

.typing-indicator span:nth-child(1) {
  animation-delay: -0.32s;
}

.typing-indicator span:nth-child(2) {
  animation-delay: -0.16s;
}

@keyframes typing {
  0%, 80%, 100% {
    transform: scale(0);
  }
  40% {
    transform: scale(1);
  }
}

.input-container {
  border-top: 1px solid #e8e8e8;
  padding: 12px;
  background: #fff;
}

.input-box {
  max-width: 800px;
  margin: 0 auto;
}

.input-actions {
  margin-top: 6px;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.input-tips {
  font-size: 10px;
  color: #999;
}

/* 滚动条样式 */
.messages-container::-webkit-scrollbar {
  width: 6px;
}

.messages-container::-webkit-scrollbar-track {
  background: #f1f1f1;
}

.messages-container::-webkit-scrollbar-thumb {
  background: #c1c1c1;
  border-radius: 3px;
}

.messages-container::-webkit-scrollbar-thumb:hover {
  background: #a8a8a8;
}

@media (max-width: 768px) {
  .features-grid {
    grid-template-columns: 1fr;
    max-width: 300px;
  }
  
  .assistant-message {
    max-width: 95%;
  }
  
  .user-message {
    max-width: 85%;
  }
  
  .header-title h2 {
    font-size: 20px;
  }
}
</style>